package com.htgd.gardenexpo.controller;


import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConCalendar;
import com.htgd.gardenexpo.entity.PageQuery;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.GetAmazonS3Client;
import com.htgd.gardenexpo.utils.SecurityParameter;
import com.htgd.gardenexpo.utils.UniteUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 活动日历 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-02-06
 */
@RestController
@RequestMapping("/api/calendar")
@Api(tags = "日历接口")
public class GeConCalendarController {
    @Value("${upload.absolute.url}")
    public String absolute_url;
    @Value("${local.url}")
    public String local_url;

    @Value("${upload.url}")
    public String upload_url;
    @Value("${spring.file-storage.aws-s3[0].bucket-name}")
    public String bucket_name;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private GetAmazonS3Client getAmazonS3Client;

    @Resource
    private GeConCalendarService geConCalendarService;

    @Resource
    private GeConNewsAccessService geConNewsAccessService;

    @Resource
    private GeConNewsUploadService geConNewsUploadService;

    @Resource
    private GeConNewsFeedbackService geConNewsFeedbackService;

    @Autowired
    private GeBaseDictService geBaseDictService;


    /**
     * 新增新闻
     */
    @PostMapping(value = "/add")
    @ApiOperation("添加")
    public CommonResult<JSONObject> add(@RequestBody GeConCalendar geConCalendar) {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String uploadIds = geConCalendar.getUploadIds();
            geConCalendarService.insert(geConCalendar);
//            if (!uploadIds.equals("")){
//                for (String uploadId:uploadIds.split(",")){
//                    GeConNewsUpload geConNewsUpload=geConNewsUploadService.queryById(Integer.parseInt(uploadId));
//                    geConNewsUpload.setNewId(geConCalendar.getNewId());
//                    geConNewsUploadService.update(geConNewsUpload);
//                }
//            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }

        return result;
    }
    /**
     * 上传图片
     */
/*    @PostMapping(value = "/uploadNewsPhoto")
    public String uploadNewsPhoto(@RequestParam(value = "file") MultipartFile file){
        if (file.isEmpty()) {
            System.out.println("文件为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = absolute_url; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return local_url+"upload/"+fileName;
    }*/
//    /**
//     * 上传文件
//     */
//    @PostMapping(value = "/uploadNewsFile")
//    public GeConNewsUpload uploadNewsFile(@RequestParam(value = "file") MultipartFile file){
//
//        GeConNewsUpload geConNewsUpload = new GeConNewsUpload();
//        String fileName = file.getOriginalFilename();  // 文件名
//        geConNewsUpload.setFilename(fileName);
//        FileInfo fileInfo=fileStorageService.of(file)
//                .setPlatform("aws-s3-1")
//                .setSaveFilename(System.currentTimeMillis()+"/"+file.getOriginalFilename())
//                .upload();
//        geConNewsUpload.setFilePath(upload_url+fileInfo.getFilename());
//        geConNewsUploadService.insert(geConNewsUpload);
//        return geConNewsUpload;
//    }

    /**
     * 编辑新闻
     */
    @PostMapping(value = "/edit")
    public CommonResult<JSONObject> edit(@RequestBody GeConCalendar geConCalendar) {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            String uploadIds = geConCalendar.getUploadIds();
            geConCalendarService.updateEntity(geConCalendar);
//            if (!uploadIds.equals("")&&uploadIds.contains(",")){
//                geConNewsUploadService.deleteByIds(uploadIds.split(","),geConCalendar.getNewId());
//                for (String uploadId:uploadIds.split(",")){
//                    GeConNewsUpload geConNewsUpload=geConNewsUploadService.queryById(Integer.parseInt(uploadId));
//                    geConNewsUpload.setNewId(geConCalendar.getNewId());
//                    geConNewsUploadService.update(geConNewsUpload);
//                }
//            }else {
//                geConNewsUploadService.deleteByNewId(geConCalendar.getNewId());
//            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除新闻
     */
    @PostMapping(value = "/delete")
    public CommonResult<JSONObject> delete(int newId) {
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConCalendarService.deleteById(newId);
//            List<GeConNewsUpload> list=geConNewsUploadService.queryByNewsId(newId);
//            for (GeConNewsUpload geConNewsUpload:list){
//                String filepath=geConNewsUpload.getFilePath();
//                String path=filepath.substring(filepath.indexOf(bucket_name+"/"),filepath.length()-1);
//                getAmazonS3Client.delete(path);
//            }
//            geConNewsUploadService.deleteByNewId(newId);
//            geConNewsFeedbackService.deleteById(newId);
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

//    /**
//     * 批量删除新闻
//     */
////    @PostMapping(value = "/deleteAll")
//    public CommonResult<JSONObject> deleteAll(String newIds){
//        CommonResult<JSONObject> result = new CommonResult<>();
//        try {
//            if (newIds!=null&&!newIds.equals("")){
//                for (String promo:newIds.split(",")){
//                    int promoId= Integer.parseInt(promo);
//                    delete(promoId);
//                }
//            }
//
//            result.setCode(200);
//        }catch (Exception e){
//            e.printStackTrace();
//            result.setCode(500);
//        }
//        return result;
//    }

    /**
     * 历史新闻检索列表
     */
    @PostMapping(value = "/list")
    @SecurityParameter
    public CommonResult<List<GeConCalendar>> list(@RequestBody PageQuery pageQuery) {
        CommonResult<List<GeConCalendar>> result = new CommonResult<>();
        try {
            pageQuery.setPageNum((pageQuery.getPageNum() - 1) * pageQuery.getPageSize());
            List<GeConCalendar> list = geConCalendarService.getAllNewsByValue(pageQuery);
            if (list != null && list.size() > 1) {
                for (GeConCalendar geConCalendar : list) {
                    String content = UniteUtils.stripHtml(geConCalendar.getNewContent().toString());
                    if (!content.equals("")) {
                        geConCalendar.setNewContent(content.substring(0, content.length() > 200 ? 200 : content.length()));
                    } else {
                        geConCalendar.setNewContent("");
                    }
                    geConCalendar.setRecommendTypeText(geBaseDictService.getRecommendTypeText(geConCalendar.getRecommendType()));
                }
            }
            pageQuery.setPageSize(0);
            List<GeConCalendar> list1 = geConCalendarService.getAllNewsByValueNoContent(pageQuery);
            result.setCode(200);
            result.setData(list);
            result.setMessage(String.valueOf(list1.size()));
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 新闻发布
     */
    @GetMapping(value = "/release")
    public CommonResult<JSONObject> release() {
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻取消发布
     */
    @GetMapping(value = "/unpublish")
    public CommonResult<JSONObject> unpublish() {
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻排序
     */
    @GetMapping(value = "/sort")
    public CommonResult<List<Map<String, Object>>> sort() {
        CommonResult<List<Map<String, Object>>> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻置顶
     */
    @GetMapping(value = "/top")
    public CommonResult<JSONObject> top() {
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻轮播
     */
    @GetMapping(value = "/carousel")
    public CommonResult<JSONObject> carousel() {
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }

    /**
     * 新闻审核
     */
    @GetMapping(value = "/review")
    public CommonResult<JSONObject> review( GeConCalendar geConCalendar){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            GeConCalendar geConNews1=geConCalendarService.queryById(geConCalendar.getNewId());
            geConNews1.setStatus(geConCalendar.getStatus());
            if (geConCalendar.getPublisherId()!=null){
                geConNews1.setPublisherId(geConCalendar.getPublisherId());
            }
            if (geConCalendar.getAuthUserId()!=null){
                geConNews1.setAuthUserId(geConCalendar.getAuthUserId());
            }
            String feedback=geConCalendar.getFeedback();
            geConNews1.setReleasetime(new Date());
            geConCalendarService.updateEntity(geConNews1);
//            if (!feedback.equals("")){
//                GeConNewsFeedback geConNewsFeedback=new GeConNewsFeedback();
//                geConNewsFeedback.setNewId(geConCalendar.getNewId());
//                geConNewsFeedback.setContent(feedback);
//                geConNewsFeedbackService.insert(geConNewsFeedback);
//            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

//    /**
//     * 审核失败反馈
//     */
//    @GetMapping(value = "/feedbackInfo")
//    public CommonResult<List<GeConNewsFeedback>> feedbackInfo(int newsId){
//        CommonResult<List<GeConNewsFeedback>> result = new CommonResult<>();
//        try{
//            List<GeConNewsFeedback> list=geConNewsFeedbackService.getinfoByNewId(newsId);
//            result.setData(list);
//            result.setCode(200);
//        }catch (Exception e){
//            e.printStackTrace();
//            result.setCode(500);
//        }
//        return result;
//    }

//
//    /**
//     * 新闻轮播列表
//     */
//    @GetMapping(value = "/carousellist")
//    public CommonResult<List<GeConCalendar>> carousellist(){
//        CommonResult<List<GeConCalendar>> result = new CommonResult<>();
//        try{
//            List<GeConCalendar> list=geConCalendarService.getAllHomeNews();
//            result.setData(list);
//            result.setCode(200);
//        }catch (Exception e){
//            e.printStackTrace();
//            result.setCode(500);
//        }
//        return result;
//    }
//
//
    /**
     *  新闻详情
     */
    @PostMapping(value = "/details")
    @SecurityParameter
    public CommonResult<Map<String,Object>> details(@RequestBody String s){
        CommonResult<Map<String, Object>> result = new CommonResult<>();
        try{
            Integer newId= JSON.parseObject(s).getInteger("newId");
            Map<String, Object> map = new HashMap<>();
            GeConCalendar geConCalendar=geConCalendarService.queryById(newId);
            map.put("news",geConCalendar);
//            List<GeConNewsUpload> geConNewsUpload=geConNewsUploadService.queryByNewsId(newId);
//            map.put("upload",geConNewsUpload);
            PageQuery pageQuery = new PageQuery();
            pageQuery.setReviewStatus("3");
            pageQuery.setPageSize(0);
            List<GeConCalendar> nlist=geConCalendarService.getAllNewsByValueNoContent(pageQuery);
            List<GeConCalendar> list = new ArrayList<>();
            for (int i=0;i<nlist.size();i++){
                GeConCalendar geConNews1=nlist.get(i);
                if (newId==geConNews1.getNewId()){
                    if (nlist.size() >= 3) {
                        if (i < nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            list.add(Conversion(nlist.get(i + 3)));
                            map.put("more", list);
                        } else if (i == nlist.size() - 3) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            list.add(Conversion(nlist.get(i + 2)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 2) {
                            if (i != 0) {
                                map.put("up", Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", Conversion(nlist.get(i + 1)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(0)));
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        } else if (i == nlist.size() - 1) {
                            if (i != 0) {
                                map.put("up",Conversion(nlist.get(i - 1)));
                            } else {
                                map.put("up", "");
                            }
                            map.put("down", "");
                            list.add(Conversion(nlist.get(0)));
                            if (nlist.size() != 3) {
                                list.add(Conversion(nlist.get(1)));
                            }
                            map.put("more", list);
                        }
                    } else {
                        if (i == 0 && nlist.size() > 1) {
                            map.put("up", "");
                            map.put("down", Conversion(nlist.get(i + 1)));
                        } else if (i == 0 && nlist.size() == 1) {
                            map.put("up", "");
                            map.put("down", "");
                        } else {
                            map.put("up", Conversion(nlist.get(i - 1)));
                            map.put("down", "");
                        }
                        map.put("more", "");
                    }
                    break;
                }
            }
            result.setData(map);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    public GeConCalendar  Conversion(GeConCalendar geConCalendar){
        GeConCalendar geConNews1=geConCalendarService.queryById(geConCalendar.getNewId());
        String content=UniteUtils.stripHtml(geConNews1.getNewContent().toString());
        if (!content.equals("")){
            geConNews1.setNewContent(content.substring(0,content.length()>200?200:content.length()));
        }else {
            geConNews1.setNewContent("");
        }
        return geConNews1;
    }
//
//    /**
//     * 统计新闻点击
//     */
//    @PostMapping("/addAccess")
//    @SecurityParameter
//    public CommonResult<JSONObject> addAccess(@RequestBody String s){
//        CommonResult<JSONObject> result = new CommonResult<>();
//        try {
//            Integer newsId=JSON.parseObject(s).getInteger("newId");
//            GeConNewsAccess geConNewsAccess = new GeConNewsAccess();
//            geConNewsAccess.setNewsId(newsId);
//            geConNewsAccessService.insert(geConNewsAccess);
//            result.setCode(200);
//        }catch (Exception e){
//            e.printStackTrace();
//            result.setCode(500);
//        }
//        return result;
//    }
//
//    @GetMapping("/addHit")
//    public CommonResult<JSONObject> addHit(@RequestParam String newId){
//        CommonResult<JSONObject> result = new CommonResult<>();
//        GeConNewsAccess geConNewsAccess=new GeConNewsAccess();
//        geConNewsAccess.setNewsId(Integer.valueOf(newId));
//        geConNewsAccessService.insert(geConNewsAccess);
//        result.setCode(200);
//        result.setMessage("增加成功");
//        return result;
//    }
//
}
